//
//  CGNetManage.m
//  Onskysell
//
//  Created by cg on 17/3/6.
//  Copyright © 2017年 cg. All rights reserved.
//

#import "CGNetManage.h"
#import "NSString+Helpers.h"
#import "Reachability.h"

@implementation CGNetManage{
    AFHTTPSessionManager *httpManager;
}

+ (CGNetManage *)shared{
    static CGNetManage *netManage = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        netManage = [[CGNetManage alloc]init];
    });
    return netManage;
}

+ (void)httpPostImg:(UIImage *)img compress:(CGFloat)compress success:(LJCompleteBlock)success fail:(LJFailBlock)fail
{
    __block NSData *data = UIImageJPEGRepresentation (img, compress);
    NSString *postImgUrl = [NSString stringWithFormat:@"%@%@", BaseURL,@"AppService/UpateRefundImages"];
    AFHTTPSessionManager *requestManager = [AFHTTPSessionManager manager];
    requestManager.requestSerializer = [AFHTTPRequestSerializer serializer];
    requestManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [requestManager POST:postImgUrl parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:data name:@"file" fileName:@"image.jpg" mimeType:@"text/html"];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(task,responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (fail) {
            fail(task, error);
        }
    }];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        NSURLCache *sharedCache =
        [[NSURLCache alloc] initWithMemoryCapacity:2 * 1024 * 1024
                                      diskCapacity:2 * 1024 * 1024
                                          diskPath:nil];
        [NSURLCache setSharedURLCache:sharedCache];
        
        [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
        
        httpManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:BaseURL]];
        
        AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
        securityPolicy.validatesDomainName = NO;
        securityPolicy.allowInvalidCertificates = YES;
        httpManager.securityPolicy = securityPolicy;
        
        [httpManager.requestSerializer setTimeoutInterval:60.0f];
        
        [httpManager.requestSerializer setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
        NSOperationQueue *operationQueue = httpManager.operationQueue;
        
        //        httpManager.responseSerializer = [AFJSONResponseSerializer serializer];
        httpManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/plain", nil];
//        AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
//        securityPolicy.allowInvalidCertificates = YES;
//        httpManager.securityPolicy = securityPolicy;
        [httpManager.reachabilityManager
         setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
             switch (status) {
                 case AFNetworkReachabilityStatusReachableViaWWAN:
                 case AFNetworkReachabilityStatusReachableViaWiFi:
                     [operationQueue setSuspended:NO];
                     break;
                 case AFNetworkReachabilityStatusNotReachable:
                 case AFNetworkReachabilityStatusUnknown:
                     [operationQueue setSuspended:YES];
                     break;
             }
         }];
    }
    return self;
}

+ (BOOL) isReachable{
    //return [[AFNetworkReachabilityManager managerForDomain:BaseURL] isReachable];
    
    BOOL isExistenceNetwork = YES;
//    Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = NO;
            //NSLog(@"notReachable");
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = YES;
            //NSLog(@"WIFI");
            break;
        case ReachableViaWWAN:
            isExistenceNetwork = YES;
            //NSLog(@"3G");
            break;
    }
    
    return isExistenceNetwork;
}


- (NSURLSessionTask *)httpPost:(NSString *)url params:(NSDictionary *)paramsDic completed:(HZCompletedBlock)completeBlock failed:(HZFailedBlock )failedBlock error:(HZErrorBlock) errorBlock{
    return [httpManager POST:url parameters:paramsDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([NSString isNotNULLOrNotNilOrNotEmpty:responseObject[@"code"]] && [@"200" isEqualToString: responseObject[@"code"]]) {
            completeBlock(responseObject[@"message"], responseObject[@"data"]);
        } else {
            NSString *resultcode = [NSString stringWithFormat:@"%@", responseObject[@"code"]];
            id resultMsg = responseObject[@"message"];
            failedBlock(resultcode,resultMsg);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        errorBlock(@"网络错误");
    }];
}

- (NSURLSessionTask *)httpGet:(NSString *)url params:(NSDictionary *)paramsDic completed:(HZCompletedBlock)completeBlock failed:(HZFailedBlock )failedBlock error:(HZErrorBlock) errorBlock{
    return [httpManager GET:url parameters:paramsDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([NSString isNotNULLOrNotNilOrNotEmpty:responseObject[@"code"]] && [@"200" isEqualToString: responseObject[@"code"]]) {
            completeBlock(responseObject[@"message"], responseObject[@"data"]);
        } else {
            NSString *resultcode = [NSString stringWithFormat:@"%@", responseObject[@"code"]];
            id resultMsg = responseObject[@"message"];
            
            failedBlock(resultcode,resultMsg);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        errorBlock(@"网络错误");
    }];
    
}

- (void)httpCheckVersionWithCompleted:(void(^)(NSDictionary *))completeBlock fail:(void(^)(NSError *))failBlock
{
    [httpManager GET:[CGUrlManage getCheckVersionUrl] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        completeBlock(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failBlock(error);
    }];
}

- (void)httpInitPageWithUrlLink:(NSString *)urlLink Completed:(void(^)(NSDictionary *))completeBlock fail:(void(^)(NSError *))failBlock
{
    [httpManager GET:urlLink parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        completeBlock(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failBlock(error);
    }];
}

- (void)httpGetHomeDataWithCompleted:(void(^)(NSDictionary *))completeBlock fail:(void(^)(NSError *))failBlock
{
    [httpManager GET:[CGUrlManage loadHoneIndex] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        completeBlock(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failBlock(error);
    }];
}

- (void)httpGetCateListWithCompleted:(void(^)(NSArray *))completeBlock fail:(void(^)(NSError *))failBlock
{
    [httpManager GET:[CGUrlManage loadCateList] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        completeBlock(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failBlock(error);
    }];
}

- (void)httpGetGoodsListWithParams:(NSDictionary *)paramsDic Completed:(void(^)(NSArray *))completeBlock fail:(void(^)(NSError *))failBlock
{
    [httpManager POST:[CGUrlManage loadProductList] parameters:paramsDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        completeBlock(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failBlock(error);
    }];
}

- (void)httpGetGoodsDetailWithParams:(NSDictionary *)paramsDic Completed:(void(^)(NSDictionary *))completeBlock fail:(void(^)(NSError *))failBlock
{
    [httpManager POST:[CGUrlManage loadProductDetail] parameters:paramsDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        completeBlock(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failBlock(error);
    }];
}

- (void)httpGetOrderListWithParams:(NSDictionary *)paramsDic Completed:(void(^)(NSDictionary *))completeBlock fail:(void(^)(NSError *))failBlock
{
    [httpManager POST:[CGUrlManage LoadOrderList] parameters:paramsDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        completeBlock(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failBlock(error);
    }];
}

- (void)httpLoginWithParams:(NSDictionary *)paramsDic Completed:(void(^)(NSDictionary *))completeBlock fail:(void(^)(NSError *))failBlock
{
    [httpManager POST:Login_Url_1 parameters:paramsDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        completeBlock(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failBlock(error);
    }];
}

- (void)httpAddCart:(NSDictionary *)paramsDic Completed:(void(^)(NSDictionary *))completeBlock fail:(void(^)(NSError *))failBlock
{
    [httpManager POST:Add_Cart_1 parameters:paramsDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        completeBlock(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failBlock(error);
    }];
}
@end
